package system

import (
	"fmt"

	"github.com/asynkron/protoactor-go/actor"
)

// ActorSystem represents the DataFlare actor system
type ActorSystem struct {
	// System is the underlying ProtoActor system
	System *actor.ActorSystem
	// SystemSupervisor is the system supervisor PID
	SystemSupervisor *actor.PID
}

// NewActorSystem creates a new actor system
func NewActorSystem() (*ActorSystem, error) {
	// Create actor system
	system := actor.NewActorSystem()
	actorSystem := &ActorSystem{
		System: system,
	}

	// Create system supervisor
	supervisorProps := actor.PropsFromProducer(func() actor.Actor {
		return NewSystemSupervisor()
	})

	systemSupervisor, err := system.Root.SpawnNamed(supervisorProps, "system-supervisor")
	if err != nil {
		return nil, fmt.Errorf("failed to spawn system supervisor: %w", err)
	}

	actorSystem.SystemSupervisor = systemSupervisor

	return actorSystem, nil
}

// Shutdown shuts down the actor system
func (s *ActorSystem) Shutdown() error {
	// Stop system supervisor
	if s.SystemSupervisor != nil {
		s.System.Root.Stop(s.SystemSupervisor)
	}

	return nil
}
